package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;
    //采购项Service
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("id", key).or().like("assignee_name", key);
            //模糊条件匹配以名字为准，检索条件固定值为id
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            //为空的话新建一个
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.ProductStatusEnum.CREATED.getCode());//默认是0
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);//默认调用新增功能
            purchaseId = purchaseEntity.getId();
        }
        //数据库查询所有要合并的采购单，然后过滤所有大于 [已分配] 状态的订单，就是说已经去采购了就不能改了
        //TODO 确认采购单状态是否是0或者1才可以合并
        List<Long> items = mergeVo.getItems();// 获取带过来的采购需求
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        List<PurchaseDetailEntity> detailEntities  = purchaseDetailService.getBaseMapper().selectBatchIds(items).stream().filter(entity -> {
            // 如果没还去采购，就可以更改 // 采购需求有问题可以再去重新采购
            return entity.getStatus() < WareConstant.ProductDetailStatusEnum.BUYING.getCode()
                    || entity.getStatus() == WareConstant.ProductDetailStatusEnum.HASERROR.getCode();
        }).collect(Collectors.toList());
        // 得到过滤好的需求id
        items = detailEntities.stream().map(entity ->
            entity.getId()).collect(Collectors.toList());
        if (items == null || items.size() == 0) {
            return;
        }
        // 设置仓库id
        purchaseEntity.setWareId(detailEntities.get(0).getWareId());
        // 采购单得是同个仓库的
        Long finalPurchaseId = purchaseId;
        // 给采购需求设置所属采购单和状态等信息
        List<PurchaseDetailEntity> collect1 = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.ProductDetailStatusEnum.ASSIGNED.getCode());
            purchaseDetailEntity.setId(item);//设置循环读出来的采购需求id
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect1);
        //合并完采购单后，修改采购单时间
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    @Override
    public void received(List<Long> ids) {
        //1.首先如果 先领了5号采购单，那么先改变状态，有关5号采购单的所有需求状态 也得改掉，也必须先确认 是新建或者已分配状态才能领取
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            //是不是新建 已分配

            return byId;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.ProductDetailStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.ProductDetailStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(item -> {
            item.setStatus(WareConstant.ProductStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());//这些采购单才是想要的，改变他们的状态
        //2.改变采购单的状态
        this.updateBatchById(collect);
        //3.改变采购项的状态
        collect.forEach((item) -> {
            List<PurchaseDetailEntity> entities = purchaseDetailService.updateDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = entities.stream().map(entity -> {
                PurchaseDetailEntity ent = new PurchaseDetailEntity();
                ent.setId(entity.getId());
                ent.setStatus(WareConstant.ProductDetailStatusEnum.BUYING.getCode());
                return ent;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });
    }

    @Override
    public void done(PurchaseDoneVo doneVo) {

        Long id = doneVo.getId();

        //2.改变采购项状态
        Boolean flag =true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
        for (PurchaseItemDoneVo item : doneVo.getItems()) {
            if (item.getStatus() == WareConstant.ProductDetailStatusEnum.HASERROR.getCode()){
                //如果是4 说明失败
                flag=false;
                detailEntity.setStatus(WareConstant.ProductDetailStatusEnum.HASERROR.getCode());
            }else {
                detailEntity.setStatus(WareConstant.ProductDetailStatusEnum.FINISH.getCode());
                //成功就入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());//查出当前详细信息
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
       /* doneVo.getItems().forEach(item->{
            if (item.getStatus() == WareConstant.ProductDetailStatusEnum.HASERROR.getCode()){
                //如果是4 说明失败
                flag=false;
                detailEntity.setStatus(WareConstant.ProductDetailStatusEnum.HASERROR.getCode());
            }else {
                detailEntity.setStatus(WareConstant.ProductDetailStatusEnum.FINISH.getCode());
                detailEntity.setId(item.getItemId());
                updates.add(detailEntity);
            }
        });*/
        purchaseDetailService.updateBatchById(updates);
        //采购项更新完成

        //1.改变采购单状态
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(id);
        entity.setStatus(flag?WareConstant.ProductStatusEnum.FINISH.getCode():WareConstant.ProductStatusEnum.HASERROR.getCode());
        entity.setUpdateTime(new Date());
        this.updateById(entity);
        //3.成功采购的进行入库
    }

}